<?php
class SearchForm extends AbstractFilter {

	protected $_criteria = null;

	public $query;
	
	public function init($criteria) {
		$this->_criteria = $criteria;
		if (isset($_GET['q'])) $this->query = $_GET['q'];
	}
	
	public function apply() {
		$this->query = trim($this->query);
		
		if (!empty($this->query)) {
			// filter post which contain all word in query
			$words = preg_split('/\s+/i', $this->query);
			$cond1 = $cond2 = '';
			foreach($words as $w) {
				$cond1 .= "title LIKE '%$w%' AND ";
				$cond2 .= "content LIKE '%$w%' AND ";
			}
			$cond = '('.trim($cond1, ' AND ').') OR ('.trim($cond2, ' AND ').')';
			$this->_criteria->addCondition($cond, 'AND', 'search');
		}
	}

	public function getTemplate() {
		return '/catalog/search';
	}
}